package com.pochogastos.servlets;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.jasypt.util.password.BasicPasswordEncryptor;

import com.pochogastos.dao.UsuarioDAO;
import com.pochogastos.model.Usuario;

/**
 * Servlet implementation class MiPerfil
 */
public class MiPerfil extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public MiPerfil() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Usuario u = (Usuario)request.getSession().getAttribute("USUARIO");
			String forward = "/miPerfil.jsp";
			
			if(u==null){
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login?accion=");
				rd.forward(request, response);
				
			}else{
				RequestDispatcher rd = getServletContext().getRequestDispatcher(forward);
				rd.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/error.jsp");
			request.getSession().setAttribute("ERROR", e.getMessage());
			rd.forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		File file = null;
		try {
			Usuario u = (Usuario)request.getSession().getAttribute("USUARIO");
			String forward = "/miPerfil.jsp";
			
			if(u==null){
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/Login?accion=");
				rd.forward(request, response);
			}else{
				String email = "";
				String password = "";
				String encPass = "";
				String nombre = "";
				String telefono = "";
				
				List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
				for (FileItem item : items) {
		            if (item.isFormField()) {
		               String fieldname = item.getFieldName();
		               String fieldvalue = item.getString();
		               if(fieldname.equalsIgnoreCase("email"))
		            	   email = fieldvalue;
		               else if(fieldname.equalsIgnoreCase("clave"))
		            	   password = fieldvalue;
		               else if(fieldname.equalsIgnoreCase("nombre"))
		            	   nombre = fieldvalue;
		               else if(fieldname.equalsIgnoreCase("telefono"))
		            	   telefono = fieldvalue;
		            } else {
		                // Process form file field (input type="file").
		            	
		                String filename = item.getName();
		                if(!"".equalsIgnoreCase(filename)){
			                filename = String.format("%s%s%s", request.getServletContext().getRealPath("/img"), File.separatorChar, filename);
			                file = new File(filename);
			                item.write(file);
		                }
		            }
		        }
				
				if(!"".equalsIgnoreCase(password)){
					BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
					encPass = passwordEncryptor.encryptPassword(password);
					
				}
				UsuarioDAO.getInstance().updateUsuario(u.getId(), email, telefono, file, encPass,nombre);
				u.setMail(email);
				u.getPerfil().setTelefono(telefono);
				u.setNombre(nombre);
				if(!"".equalsIgnoreCase(password))
					u.setPassword(encPass);
				request.getSession().setAttribute("USUARIO",u);
				if(file!=null && file.exists())
					file.delete();
				RequestDispatcher rd = getServletContext().getRequestDispatcher(forward);
				rd.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/error.jsp");
			request.getSession().setAttribute("ERROR", e.getMessage());
			if(file!=null && file.exists())
				file.delete();
			rd.forward(request, response);
		}
	}

}
